package com.atguigu.gmall.product.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.atguigu.gmall.common.config.minio.properties.MinioProperties;
import com.atguigu.gmall.product.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    MinioClient minioClient;

    @Transactional
    @Override
    public String upload(MultipartFile multipartFile) {



        String filename = multipartFile.getOriginalFilename();
        String date = DateTime.now().toString("yyyy/MM/dd");
        String name = date + "/" + UuidUtils.generateUuid().toString().replace("-","").substring(5) + filename;
        String type = multipartFile.getContentType();

        String path = minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + name;
        long size = multipartFile.getSize();


        try {
            InputStream inputStream = multipartFile.getInputStream();

            PutObjectOptions options= new PutObjectOptions(size,-1);
            options.setContentType(type);
            minioClient.putObject(minioProperties.getBucket(), name,inputStream,options);

            return path;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
